import Modal from 'ant-design-vue/es/modal/index.js';
import { loadPlugin } from './AMapUtils.js';
import { tap } from '../../../utils/index.js';

export class AMapMouseTool {
  constructor(map, option) {
    this.map = map;
    this.option = (typeof option === 'object' && option) || {};
  }
  async getMouseTool() {
    if (!AMap.MouseTool) {
      await loadPlugin(['AMap.MouseTool']);
    }
    if (!this.mousetool) {
      this.mousetool = new AMap.MouseTool(this.map);
      this.mousetool.on('draw', (e) => {
        this.polyType = null;
        this.mousetool.close(false);
        tap(this.option.onEnd, e);
      });
    }
    return await this.mousetool;
  }
  async start(polyType, polyOption) {
    const mouseTool = await this.getMouseTool();
    if (typeof mouseTool[polyType] !== 'function') {
      throw new Error('绘制类型不正确');
    }
    this.polyType = polyType;
    mouseTool[polyType](polyOption);
    tap(this.option.onStart);
  }
  stop() {
    return new Promise((resolve) => {
      if (this.mousetool && typeof this.mousetool.close === 'function') {
        if (this.polyType) {
          return Modal.confirm({
            title: '结束绘制并清除当前绘制图形？',
            content: '绘制没有正常结束，请双击鼠标左键或单击右键以结束',
            cancelText: '取消',
            okText: '确定',
            onOk: () => {
              this.mousetool.close(true);
              tap(this.option.onEnd, null, resolve);
            },
            onCancel: () => {
              resolve(false);
            },
          });
        }
        this.mousetool.close(false);
      }
      tap(this.option.onEnd, null, resolve);
    });
  }
}
